package cn.crism.commons;

import cn.crism.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String url = request.getRequestURL().toString();
        ModelAndView mv;
        String msg = "SYSTEM ERROR.";
        /* 数据异常返回json数据 */
        if (url.endsWith(".m")) {
            if (e instanceof PermissionException || e instanceof PermissionException){
                JsonData result = JsonData.fail(e.getMessage());
                mv = new ModelAndView("jsonView",result.toMap());
            }else {
                log.error("UNKNOWN DATA Exception. URL: " + url,e);
                JsonData result = JsonData.fail(msg);
                mv = new ModelAndView("jsonView",result.toMap());
            }
        } else if (url.endsWith(".v")){
            log.error("UNKNOWN VIEW Exception. URL: " + url,e);
            JsonData result = JsonData.fail(msg);
            /* 页面异常 寻找 exception 文件 */
            mv = new ModelAndView("exception",result.toMap());
        }else {
            log.error("UNKNOWN Exception. URL: " + url,e);
            JsonData result = JsonData.fail(msg);
            mv = new ModelAndView("jsonView",result.toMap());
        }
        return mv;
    }
}